from flask import Blueprint, jsonify, request, current_app
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from app.models import db, User
from werkzeug.security import generate_password_hash, check_password_hash
import datetime
import os
import uuid

# 认证API蓝图
auth_api = Blueprint('auth_api', __name__, url_prefix='/auth')

@auth_api.route('/register', methods=['POST'])
def register():
    """用户注册API"""
    data = request.get_json()

    print(data)

    if not data or 'username' not in data or 'email' not in data or 'password' not in data:
        return jsonify({"code" : 404, "message": "缺少必要参数"})
    
    # 检查用户名和邮箱是否已存在
    existing_user = User.query.filter((User.name == data['username']) | 
                                    (User.email == data['email'])).first()
    if existing_user:
        return jsonify({"code": 409, "message": "用户名或邮箱已被注册"})
    
    # 创建新用户，密码加密存储
    hashed_password = generate_password_hash(data['password'])
    new_user = User(
        name=data['username'],
        email=data['email'],
        password=hashed_password
    )
    
    db.session.add(new_user)
    db.session.commit()
    
    return jsonify({"code": 200, "message": "注册成功"})

@auth_api.route("/captcha",methods=['GET'])
def captcha():
    """获取验证码API"""
    # 这里可以集成验证码生成逻辑

    return
    

@auth_api.route('/login', methods=['POST'])
def login():
    """用户登录API"""
    data = request.get_json()
    
    if not data or 'username' not in data or 'password' not in data:
        return 401
    
    user = User.query.filter_by(name=data['username']).first()
    
    if user and check_password_hash(user.password, data['password']):
        # 创建JWT访问令牌，有效期24小时
        access_token = create_access_token(
            identity=str(user.id),
            expires_delta=datetime.timedelta(hours=24)
        )
        
        return jsonify({
            "code": 200,
            "message": "登录成功",
            "data": {
                "access_token": access_token
            },
            "originurl": "/auth/login"
        })
    else:
        return 401

# @auth_api.route('/profile', methods=['GET'])
# @jwt_required()
# def get_profile():
#     """获取当前用户信息"""
#     user_id = get_jwt_identity()
#     user = User.query.get_or_404(user_id)
    
#     return jsonify({
#         'user': {
#             'id': user.id,
#             'name': user.name,
#             'email': user.email
#         }
#     }), 200

@auth_api.route('/password', methods=['POST'])
@jwt_required()
def reset_password():
    """修改用户密码API"""
    user_id = get_jwt_identity()
    id = str(request.args.get('id'))

    if user_id != id:
        # 这里应检查当前用户是否为管理员
        return 403

    user = User.query.get_or_404(id)
    data = request.json
    
    if not data or 'newPassword' not in data:
        return jsonify({"code" : 404, "message": "缺少必要参数"})

    # 更新密码
    user.password = generate_password_hash(data['newPassword'])
    user.updatedTime = datetime.datetime.now()
    db.session.commit()
    
    return jsonify({
        "code": 200,
        "message": "密码修改成功",
    })

@auth_api.route('/logout', methods=['POST'])
@jwt_required()
def logout():
    """用户登出API"""
    # 注意：JWT实际上是无状态的，服务器端无法直接"注销"令牌
    # 前端实现应该是清除存储的令牌
    # 这里我们只返回一个成功消息
    return jsonify({
        "code": 200,
        "message": "登出成功",
        "data" : True,
        "originurl": "/auth/logout"
    })

# @auth_api.route('/current-role/switch/<role>', methods=['POST'])
# @jwt_required()
# def switch_role(role):
#     """切换当前用户角色API"""
#     user_id = get_jwt_identity()
#     user = User.query.get_or_404(user_id)
    
#     # 这里需要检查用户是否有该角色的权限
#     # 实际应用中需要添加Role模型和用户角色关联
    
#     # 为简化处理，这里假设切换成功
#     return jsonify({
#         'message': f'角色已切换为{role}',
#         'current_role': role
#     }), 200

# @auth_api.route('/password/<int:user_id>', methods=['POST'])
# @jwt_required()
# def change_password():
#     """修改用户密码API"""
#     user_id = get_jwt_identity()
#     user = User.query.get_or_404(user_id)
#     data = request.json
    
#     if not data or 'oldPassword' not in data or 'newPassword' not in data:
#         return jsonify({'error': '缺少必要参数'}), 400
        
#     # 验证旧密码
#     if not check_password_hash(user.password, data['oldPassword']):
#         return jsonify({'error': '原密码不正确'}), 401
        
#     # 更新密码
#     user.password = generate_password_hash(data['newPassword'])
#     db.session.commit()
    
#     return jsonify({
#         "code": 200,
#         "message": "密码修改成功",
#     })

# @auth_api.route('/forgot-password', methods=['POST'])
# def forgot_password():
#     """忘记密码API"""
#     data = request.json
    
#     if not data or 'email' not in data:
#         return jsonify({'error': '请提供邮箱地址'}), 400
    
#     # 实际项目中，这里应该发送重置密码的邮件
#     # 此处简化处理，仅返回成功信息
#     return jsonify({
#         'message': '如果该邮箱存在，我们将发送重置密码链接'
#     }), 200

# 用户API蓝图
user_api = Blueprint('user_api', __name__, url_prefix='/user')

@user_api.route('/detail', methods=['GET'])
@jwt_required()
def get_user_detail():
    """获取用户详细信息API（已由 flask_jwt_extended 验证 token）"""
    user_id = get_jwt_identity()
    user = User.query.get_or_404(user_id)
    return jsonify({
        "code": 200,
        "message": "获取用户信息成功",
        "data": {
            "id": user.id,
            "enable" : True,
            "createdTime": user.createdTime.strftime('%Y-%m-%d %H:%M:%S') if user.createdTime else None,
            "updatedTime": user.updatedTime.strftime('%Y-%m-%d %H:%M:%S') if user.updatedTime else None,
        "profile": {
            "id"    : user.id,
            "nickname" : user.nickname,
            "gender" : user.gender,
            "avatar" : user.avatar,
            "address" : user.address,
            "email" : user.email,
            "userId" : user.id,
        },
        "roles" :[
            {
                "id" : user.id,
                "code" : 200,
                "name" : user.name,
                "enable" : True
            }
        ],
        "originurl": "/user/detail"
        }
    })

@user_api.route('/profile', methods=['PATCH'])
@jwt_required()
def update_user_profile():
    """修改用户信息API"""
    current_user_id = get_jwt_identity()
    id = str(request.args.get('id'))

    # 验证权限，用户只能修改自己的信息，或管理员可修改任何用户
    if current_user_id != id:
        # 这里应检查当前用户是否为管理员
        return 403
    
    user = User.query.get_or_404(id)
    data = request.get_json()
    
    # 更新用户信息
    if 'email' in data:
        user.email = data['email']

    if 'nickName' in data:
        user.nickname = data['nickName']
    
    if 'gender' in data:
        user.gender = data['gender']

    if 'address' in data:
        user.address = data['address']

    user.updatedTime = datetime.datetime.now()
    
    db.session.commit()
    return jsonify({'code': 200, 'message': '用户信息更新成功'})

@user_api.route('/avatar', methods=['POST'])
@jwt_required()
def get_user_avatar():
    user_id = get_jwt_identity()
    id = request.args.get('id')

    if user_id != id:
        # 这里应检查当前用户是否为管理员
        return 403
    
    # 检查文件字段
    if 'avatar' not in request.files:
        return jsonify({'code':400, 'message':'缺少 avatar 文件'}), 400
    file = request.files['avatar']
    if file.filename == '':
        return jsonify({'code':400, 'message':'未选择文件'}), 400

    # 生成唯一文件名
    ext = os.path.splitext(file.filename)[1]
    filename = f"{uuid.uuid4().hex}{ext}"
    upload_folder = current_app.config.get('UPLOAD_FOLDER', 'uploads/avatars')
    print(upload_folder)
    os.makedirs(upload_folder, exist_ok=True)
    filepath = os.path.join(upload_folder, filename)
    file.save(filepath)

    # 更新用户记录并删除旧头像
    user = User.query.get_or_404(user_id)
    if user.avatar:
        old_avatar_path = os.path.join(current_app.config.get('UPLOAD_FOLDER', 'uploads/avatars'), user.avatar.split('/')[-1])
        if os.path.exists(old_avatar_path):
            os.remove(old_avatar_path)
    user.avatar = f"/{upload_folder}/{filename}"
    db.session.commit()

    return jsonify({
        'code': 200,
        'message': '头像上传成功',
        'data': {'avatar': user.avatar}
    }), 200

# 角色API蓝图
role_api = Blueprint('role_api', __name__, url_prefix='/api/role')

# @role_api.route('/permissions/tree', methods=['GET'])
# @jwt_required()
# def get_permissions_tree():
#     """获取角色权限树API"""
#     user_id = get_jwt_identity()
    
#     # 这里需要查询用户角色和对应的权限树
#     # 实际应用中需要添加Role和Permission模型
    
#     # 模拟权限树数据
#     permissions_tree = {
#         'id': 'root',
#         'name': '权限根节点',
#         'children': [
#             {
#                 'id': 'system',
#                 'name': '系统管理',
#                 'children': [
#                     {'id': 'user_manage', 'name': '用户管理'},
#                     {'id': 'role_manage', 'name': '角色管理'}
#                 ]
#             },
#             {
#                 'id': 'content',
#                 'name': '内容管理',
#                 'children': [
#                     {'id': 'lyrics_manage', 'name': '歌词管理'},
#                     {'id': 'image_manage', 'name': '图像管理'}
#                 ]
#             }
#         ]
#     }
    
#     return jsonify({'permissions': permissions_tree}), 200
